package com.longapp.dao;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import com.longapp.fitness.R;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

public class DBManager {
    private final int BUFF_SIZE = 8192;
    private final String DATABASE_PATH = android.os.Environment.getExternalStorageDirectory().getAbsolutePath()
            + "/Fitness";
    private final String DATABASE_FILENAME = "fitness.db";
    private Context context;

    public DBManager(Context context) {
        this.context = context;
    }

    public SQLiteDatabase openDatabase() {
        try {

            String databaseFilename = DATABASE_PATH + "/" + DATABASE_FILENAME;
            File dir = new File(DATABASE_PATH);

            if (!dir.exists())
                dir.mkdirs();
            if (!new File(databaseFilename).exists()) {
                new File(databaseFilename).createNewFile();
            }

            if (!(new File(databaseFilename)).exists()) {

                InputStream is = context.getResources().openRawResource(R.raw.fitness);
                FileOutputStream fos = new FileOutputStream(databaseFilename);
                byte[] buffer = new byte[is.available()];
                int count = 0;

                while ((count = is.read(buffer)) > 0) {
                    fos.write(buffer, 0, count);
                }
                fos.flush();
                fos.close();
                is.close();
            }

            SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(databaseFilename, null);
            return database;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
